"use client";

import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { List, Timer, AlertCircle, Play, Square } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

type Result = {
  round: number;
  number: number;
  timestamp: string;
};

export function LuckyDraw() {
  const [min, setMin] = useState<string>('1');
  const [max, setMax] = useState<string>('100');
  const [isSpinning, setIsSpinning] = useState(false);
  const [isStopping, setIsStopping] = useState(false);
  const [currentNumber, setCurrentNumber] = useState<number | string>('--');
  const [results, setResults] = useState<Result[]>([]);
  
  const { toast } = useToast();
  const animationFrameId = useRef<number | null>(null);

  const handleError = (message: string) => {
    toast({
      variant: "destructive",
      title: "Invalid Input",
      description: message,
    });
  }

  const handleStart = () => {
    const minVal = parseInt(min, 10);
    const maxVal = parseInt(max, 10);

    if (isNaN(minVal) || isNaN(maxVal) || min.trim() === '' || max.trim() === '') {
      handleError('Please enter valid numbers for min and max values.');
      return;
    }
    if (minVal >= maxVal) {
      handleError('Max number must be greater than min number.');
      return;
    }
    
    setIsSpinning(true);

    const animate = () => {
        const randomNum = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
        setCurrentNumber(randomNum);
        animationFrameId.current = requestAnimationFrame(animate);
    };
    animate();
  };

  const handleStop = () => {
    if (animationFrameId.current) {
        cancelAnimationFrame(animationFrameId.current);
        animationFrameId.current = null;
    }
    setIsStopping(true);
  };
  
  useEffect(() => {
    if (!isStopping) return;

    const slowDownAndStop = async () => {
        const delays = [50, 75, 120, 180, 250, 350, 450];
        const minVal = parseInt(min, 10);
        const maxVal = parseInt(max, 10);
        let lastNumber: number = minVal;

        for (const delay of delays) {
            await new Promise(resolve => setTimeout(resolve, delay));
            const randomNum = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
            setCurrentNumber(randomNum);
            lastNumber = randomNum;
        }
        
        setResults(prev => [{ round: prev.length + 1, number: lastNumber, timestamp: new Date().toLocaleTimeString() }, ...prev]);
        setIsSpinning(false);
        setIsStopping(false);
    };

    slowDownAndStop();
    
  }, [isStopping, min, max]);

  useEffect(() => {
    return () => {
      if (animationFrameId.current) cancelAnimationFrame(animationFrameId.current);
    };
  }, []);
  
  const isDisabled = isSpinning || isStopping;

  return (
    <div className="w-full min-h-screen p-4 sm:p-6 lg:p-8 font-body text-foreground overflow-hidden">
        <main className="container mx-auto h-full max-h-[90vh] grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div className="lg:col-span-2 flex flex-col justify-between items-center text-center py-4">
                <Card className="w-full max-w-lg shadow-lg border-none">
                    <CardHeader>
                        <CardTitle className="text-3xl font-bold">Lucky Draw Decider</CardTitle>
                        <CardDescription>Set the range and start the draw!</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <form onSubmit={(e) => { e.preventDefault(); if (!isSpinning) handleStart(); }} className="space-y-4">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div className="space-y-2 text-left">
                                    <Label htmlFor="min">Min Number</Label>
                                    <Input id="min" type="number" value={min} onChange={(e) => setMin(e.target.value)} disabled={isDisabled} className="text-center text-lg" />
                                </div>
                                <div className="space-y-2 text-left">
                                    <Label htmlFor="max">Max Number</Label>
                                    <Input id="max" type="number" value={max} onChange={(e) => setMax(e.target.value)} disabled={isDisabled} className="text-center text-lg" />
                                </div>
                            </div>
                        </form>
                    </CardContent>
                </Card>

                <div className="flex flex-col items-center justify-center my-8 flex-grow">
                    <div className="text-8xl md:text-9xl font-bold text-primary tracking-tighter" style={{fontVariantNumeric: 'tabular-nums'}}>
                        {currentNumber}
                    </div>
                </div>

                <div className="w-full max-w-lg">
                    <Button
                        size="lg"
                        onClick={isSpinning ? handleStop : handleStart}
                        disabled={isStopping}
                        className="w-full text-xl font-bold py-8 transition-all duration-300 ease-in-out shadow-lg transform hover:scale-105 bg-accent hover:bg-accent/90 text-accent-foreground active:scale-100"
                    >
                        {isSpinning ? <Square className="mr-2 h-6 w-6 fill-current"/> : <Play className="mr-2 h-6 w-6 fill-current" />}
                        {isSpinning ? (isStopping ? 'Stopping...' : 'Stop') : 'Start'}
                    </Button>
                </div>
            </div>

            <Card className="lg:col-span-1 h-full flex flex-col shadow-lg border-none">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2 text-2xl">
                        <List className="h-6 w-6" />
                        Round History
                    </CardTitle>
                </CardHeader>
                <CardContent className="flex-grow overflow-hidden p-0">
                    <ScrollArea className="h-full px-6">
                        {results.length > 0 ? (
                            <ul className="space-y-3 pb-4">
                                {results.map((result) => (
                                    <li key={result.round}>
                                        <div className="flex justify-between items-center p-4 rounded-lg bg-background">
                                            <div>
                                                <p className="font-semibold text-card-foreground">Round {result.round}</p>
                                                <p className="text-xs text-muted-foreground flex items-center gap-1.5"><Timer className="h-3 w-3" /> {result.timestamp}</p>
                                            </div>
                                            <p className="text-3xl font-bold text-primary">{result.number}</p>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        ) : (
                            <div className="h-full flex items-center justify-center text-center text-muted-foreground p-4">
                                <p>Start a draw to see the results here.</p>
                            </div>
                        )}
                    </ScrollArea>
                </CardContent>
                {results.length > 0 && (
                  <CardFooter className="border-t pt-4">
                    <p className="text-sm text-muted-foreground w-full text-center">Total Rounds: {results.length}</p>
                  </CardFooter>
                )}
            </Card>
        </main>
    </div>
  );
}
